package com.snail.controller;

import com.snail.VO.CategoryVO;
import com.snail.VO.ProductVO;
import com.snail.VO.ResultVO;
import com.snail.entity.ProductCategory;
import com.snail.entity.ProductInfo;
import com.snail.service.CategoryService;
import com.snail.service.ProductService;
import com.snail.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 【swg】.
 * @Date 2017/12/8 10:32
 * @DESC
 * @CONTACT 317758022@qq.com
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public ResultVO list(){
//        1、查询所有上架商品
        List<ProductInfo> productInfoList = productService.findAllUpProducts();
//        2、从上架商品获取所有的类目type
        List<Integer> categoryTypeList = productInfoList.stream()
                                           .map(e -> e.getCategoryType())
                                            .collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.productCategoryListByType(categoryTypeList);
//        3、数据拼装
        List<CategoryVO> categoryVOList = new ArrayList<>();
        for(ProductCategory productCategory:productCategoryList){
            CategoryVO categoryVO = new CategoryVO();
            categoryVO.setCategoryName(productCategory.getCategoryName());
            categoryVO.setCategoryType(productCategory.getCategoryType());
            List<ProductVO> productVOList = new ArrayList<>();
            for(ProductInfo productInfo:productInfoList){
                //这里需要判断商品和类目的类型是否一致，否则商品将会将所有的上架商品都列出来了
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductVO productVO = new ProductVO();
                    BeanUtils.copyProperties(productInfo,productVO);
                    productVOList.add(productVO);
                }
            }
            categoryVO.setProductVOList(productVOList);
            categoryVOList.add(categoryVO);
        }
        return ResultVOUtil.success(categoryVOList);
    }
}
